package root.electronclass.electronclass

import androidx.core.view.isGone
import androidx.core.view.isVisible
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.coroutineScope
import root.electronclass.electronclass.common.util.DateUtils
import root.electronclass.electronclass.mvp.GlobalParameter
import root.electronclass.electronclass.databinding.IncludeTopBinding
import root.electronclass.electronclass.ext.CoroutineExceptionHandler
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import root.electronclass.electronclass.other.SetBgActivity
import java.util.*

/**
 *
 * @author Lokiy
 * @date 2023/1/8 13:13
 */

/**
 * 头部状态初始化
 * 获取天气，网络检测，时间等
 */
fun IncludeTopBinding.setup(lifecycle: Lifecycle, className: String? = "",showGk: Boolean = false) {
    schoolName.text = GlobalParameter.getSchoolInfo()?.schoolName?.ifEmpty { "" }
    schoolIcon.setImageURI(GlobalParameter.getSchoolInfo()?.logoFormat?.get(0)?.url)
    title.text = className.orEmpty().ifEmpty { GlobalParameter.getEcardInfo().className ?: "" }
    title.isGone = className == null //TODO 添加/日期/时间/天气/网络检测

    set.setOnClickListener {
        SetBgActivity.startActivity(this.root.context)
    }

    lifecycle.coroutineScope.launch(CoroutineExceptionHandler()) {
        while (true) {
            time2.text = DateUtils.dateToString(Calendar.getInstance().time, "HH:mm")
            delay(1000)
        }
    }

    lifecycle.coroutineScope.launch(CoroutineExceptionHandler()) {
        while (true) {
            time1.text = "${DateUtils.getDate1()} ${DateUtils.getWeek()}"
            delay(1000*10*60)
        }
    }

    GKTime(showGk)

}

fun IncludeTopBinding.title(titleRes: String? = title.text.toString(),showGk: Boolean = false) {
    title.text = titleRes
    title.isGone = titleRes == null
    GKTime(showGk)
}


fun IncludeTopBinding.GKTime(boolean: Boolean) {
    tvTimeTop.isVisible = boolean && when (GlobalParameter.getSchoolInfo().gradeNum) {
        1    -> true
        2    -> true
        else -> false
    }
    if (!GlobalParameter.getSchoolInfo().gradeName.isNullOrEmpty()) {
        tvTimeTop.text = when (GlobalParameter.getSchoolInfo().gradeNum) {
            1 -> DateUtils.CZTime()
            2 -> DateUtils.GKTime()
            else -> "0"
        }
    }else{
        tvTimeTop.isVisible = false
    }
}
